class Kvue extends EventTarget{
    constructor(options){
        super()
        this.$options = options;
        this.observer(this.$options.data)
        this.compile();
    }
    observer(data){
        Object.keys(data).forEach(key=>{
            this.defineReactive(data,key,data[key])
        })
    }
    defineReactive(data,key,value){
        let _this = this;
        Object.defineProperty(data,key,{
            enumerable: true,
            configurable:true,
            get(){
                return value
            },
            set(newValue){
                let event = new CustomEvent(key,{
                    detail:newValue
                })
                _this.dispatchEvent(event)
                value = newValue;
            }
        })
    }
    compile(){
        let el = document.querySelector(this.$options.el);
        this.compileNode(el);
    }
    compileNode(el){
        let childNodes = el.childNodes;
        console.log(childNodes,'childNodes')
        childNodes.forEach(node =>{
            // 1. 元素节点  3.文本节点
            if(node.nodeType ===1){
                let attrs = node.attributes;
                [...attrs].forEach(attr=>{
                    let attrName = attr.name;
                    let attrValue = attr.value;
                    if(attrName.startsWith('v-')){
                        attrName = attrName.substr(2)
                        if(attrName==='html'){
                            node.innerHTML = this.$options.data[attrValue]
                        }else if(attrName ==='model'){
                            node.value = this.$options.data[attrValue];
                            node.addEventListener('input',e=>{
                                this.$options.data[attrValue] = e.target.value
                            })
                        }
                    }
                })
                if(childNodes.length>0){
                    this.compileNode(node)
                }
            }else if(node.nodeType===3){
                let reg = /\{\{(.*)\}\}/
                let textContent = node.textContent;
                if(reg.test(textContent)){
                    let $1 = RegExp.$1;
                    node.textContent = node.textContent.replace(reg,this.$options.data[$1])
                    this.addEventListener($1,e=>{
                        let oldValue =  this.$options.data[$1];
                        let reg = RegExp(oldValue);
                        node.textContent = node.textContent.replace(reg,e.detail);
                    })
                }
               
            }
        })
    }
}